<!--
 * @Description: 结算页面
 * @Author: Kerwin
 * @Date: 2025-05-09 11:23:15
 * @LastEditTime: 2025-10-29 11:17:32
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="payMoney">
    <view class="card address">
      <view class="icon">
        <van-icon size="48rpx" name="location-o" />
      </view>
      <view class="address-info">
        <view>
          <text>{{ shopInfo.name }}</text>
        </view>
        <view style="font-size: 24rpx; color: #999999; margin-top: 10rpx">
          <text> {{ shopInfo.addr }}</text>
          <text> | 距离 {{ shopInfo.distance }}</text>
        </view>
      </view>
      <!-- <van-button round   plain type="primary">导航</van-button> -->
      <!-- <u-button plain type="primary" shape="square">导航</u-button> -->
    </view>

    <view class="card userInfo">
      <view class="telBox">
        <view
          ><text class="text1">联系电话</text>
          <text class="text2">用于接收订单进度，请正确填写</text>
        </view>
        <view class="telInpt">
          <u-input
            placeholder="请输入联系电话"
            v-model="phone"
            type="number"
            @blur="validatePhone"
          />
          <text v-if="phoneError" style="color: red; font-size: 24rpx">{{
            phoneError
          }}</text>
        </view>
      </view>

      <view>
        <view class="eatBox">就餐方式</view>
        <view>
          <van-radio-group
            @change="handleEatTypeChange"
            v-model="checked"
            direction="horizontal"
          >
            <view
              style="display: flex; justify-content: space-between; width: 100%"
            >
              <view
                class="chooseBox"
                :class="{ 'chooseBox-active': checked == '1' }"
              >
                <van-radio name="1" :disabled="shopData.shopBrandId == 5">
                  <view class="flexCenter"
                    ><van-icon size="30rpx" class="icon" :name="shop" />
                    <text>店内就餐</text>
                  </view>
                </van-radio>
              </view>
              <view
                class="chooseBox"
                :class="{ 'chooseBox-active': checked == '2' }"
              >
                <van-radio name="2">
                  <view class="flexCenter"
                    ><van-icon size="30rpx" class="icon" :name="zt" />自提带走
                  </view>
                </van-radio>
              </view>
            </view>
          </van-radio-group>
        </view>
      </view>
    </view>
    <!-- 预加载 -->
    <view>
      <view class="card orderInfo">
        <view class="title">
          <text>订单详情</text>

          <text @click="onClickRight">
            <van-icon style="color: #2e2e2e" size="18" name="replay"
          /></text>
        </view>
        <view v-if="!loading">
          <view v-if="!isEmpty">
            <view
              class="orderBox"
              v-for="(item, index) in moneyGoods"
              :key="item.shopProductSkuId"
            >
              <van-card
                :num="item.count"
                :desc="item.otherCheckStr"
                :title="item.skuName"
                :thumb="item.skuImage"
              >
                <template #price>
                  <text
                    style="
                      font-size: 24rpx;
                      font-weight: normal;
                      margin-right: 10rpx;
                    "
                    >x{{ item.count }}</text
                  >
                </template>
                <template #origin-price>
                  <text style="font-size: 26rpx">￥{{ item.money }}</text>
                </template>
                <template #num>
                  <text style="font-size: 28rpx; color: #fa3534"
                    ><u-tag
                      v-if="!(item.money * item.count <= item.totalMoney)"
                      size="mini"
                      text="优惠后价格"
                      type="error"
                    />￥{{ item.totalMoney }}</text
                  >
                </template>
              </van-card>
            </view>
            <view>
              <view class="price1">
                <text
                  >当前{{ enumAll.SHOPMODEL[shopMode] }}
                  {{ formatPrice1(availableTicket) }}， 商品最多抵扣 ￥{{
                    formatPrice1(totalSaveMoney)
                  }}</text
                >
              </view>
              <view class="price1 flexSpaceBetween">
                <text>{{ enumAll.SHOPMODEL[shopMode] }}抵扣</text>
                <view class="text" @click="showPop = true"
                  >{{ deductions
                  }}<text style="color: #999999">
                    <u-icon name="arrow-right"></u-icon> </text
                ></view>
              </view>
              <view
                class="price1 flexSpaceBetween"
                v-if="shopMode == 4 || shopMode == 6"
              >
                <text>服务费</text>
                <view
                  ><text style="color: #999999"> ￥{{ otherMoney }} </text>
                </view>
              </view>
              <view class="price2 flexSpaceBetween">
                <view style="color: #fa3534; font-weight: 700"
                  >已省{{ formatPrice(deductions) }}元</view
                >
                <view
                  >共{{ count }}件，实付
                  <text style="font-weight: 700; font-size: 32rpx; color: #333"
                    >￥{{ orderData.payMoney }}</text
                  >
                </view>
              </view>
            </view>
            <!-- 长来模式显示区域 -->
            <!-- <view v-if="shopMode == 6">
              <text>可用来钡余额：</text
              ><text style="color: red"> ￥{{ clBalance }} </text>
            </view> -->
            <view>
              <!-- <u-button @click="handleGoPassword">去密码</u-button> -->
              <!-- <u-button @click="handleGosuccess">去支付成功</u-button> -->
            </view>
          </view>

          <view v-else style="margin-top: 200rpx">
            <u-empty :text="loadText.loading" mode="order"></u-empty>  
          </view>
        </view>

        <view v-else>
          <u-loadmore status="loading" :load-text="loadText" />
        </view>
      </view>
    </view>
    <!-- <view v-else class="card orderInfo">
    
    </view> -->

    <view class="tijiao flexSpaceBetween">
      <text style="font-weight: 700; font-size: 32rpx; color: #333"
        >￥{{ orderData.payMoney }}</text
      >
      <view style="display: flex; align-items: center">
        <!-- <u-button
          v-if="shopMode == 6"
          @click="openClBalance"
          type="success"
          shape="circle"
          style="margin-right: 20rpx"
          >来钡余额付款</u-button
        > -->
        <u-button
          type="primary"
          style="width: 250rpx"
          shape="circle"
          @click="onsubmit"
          >提交订单</u-button
        >
      </view>
    </view>
    <u-popup v-model="showPop" border-radius="14" width="500rpx" mode="center">
      <view class="popup">
        <view class="text">{{ enumAll.SHOPMODEL[shopMode] }}抵扣</view>
        <view class="stepper">
          <van-stepper
            v-if="shopMode == 4 || shopMode == 6"
            v-model="deductions"
            input-width="150rpx"
            button-size="80rpx"
            integer
            :min="0"
            :show-plus="false"
            :show-minus="false"
            :max="Number(formatPrice1(totalSaveMoney))"
            @blur="onStepperChange"
          />
          <van-stepper
            v-if="shopMode == 1"
            v-model="deductions"
            input-width="150rpx"
            button-size="80rpx"
            :decimal-length="1"
            :min="0"
            :show-plus="false"
            :show-minus="false"
            :max="Number(formatPrice1(totalSaveMoney))"
            @blur="onStepperBlur"
          />
        </view>
      </view>
    </u-popup>
    <!-- 余额密码弹出框 -->
    <van-popup
      v-model:show="showYePay"
      position="bottom"
      round
      :style="{ height: '60%' }"
    >
      <view style="padding: 20rpx">
        <view style="text-align: center; margin-bottom: 20rpx"
          >请输入长来余额密码</view
        >
        <van-password-input
          :value="orderData.payPassword"
          info="密码为 6 位数字"
          :error-info="errorInfo"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <van-number-keyboard
          v-model="orderData.payPassword"
          :show="showKeyboard"
          @blur="showKeyboard = false"
        />
        <view>
          <u-button
            :disabled="
              !orderData.payPassword ||
              orderData.payPassword.length < 6 ||
              isPaying
            "
            type="success"
            style="margin: 20rpx 0"
            @click="handleClyePaySure"
            :loading="isPaying"
            loading-text="支付中..."
            >确认支付</u-button
          >
          <text @click="handleGoPassword" style="color: #007aff"
            >忘记密码？</text
          >
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { onReachBottom, onPageScroll, onShow, onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
//图片
import shop from '@/static/xfl/daodian.png'
import zt from '@/static/xfl/ziti.png'
//工具
import {
  useGoodStore,
  useUserStore,
  useCartStore,
  useShopInfoStore,
  useGoodsDetailStore
} from '@/store'
import { browserVersion } from '@/utils/common'
import { Decimal } from 'decimal.js'
import debounce from 'lodash/debounce'

// #region ***************** api *************************/
import { enumAll, orderApi, moneyApi, userApi } from '@/api'
import { Md5 } from 'ts-md5'

//初始化数据
const shopMode = ref()
const userStore = useUserStore()
const goodStore = useGoodStore()
const shopStore = useShopInfoStore()
const goodDetailStore = useGoodsDetailStore()
const carStore = useCartStore()
const shopInfoStore = useShopInfoStore()
const { accessToken, useShareCode } = storeToRefs(userStore)
const isApp = ref(false)
const shopData = ref() //传来的店铺数据信息
const checked = ref('1') //店内还是自提
const phone = ref('')
const phoneError = ref('')
const phoneErrorStatus = ref(false)
const chooseGoods = ref<any>([])
const moneyGoods = ref<any>([])
const orderData = ref<any>({ payMoney: 0 })
const shopInfo = ref<any>({})
const flqTicket = ref(0) //复来券
const hlhyTicket = ref(0) //花积分抵用券
const clTicket = ref(0) //现金抵用券
const deductions = ref(0)
const otherMoney = ref(0) //服务费
const loadText = ref({
  loading: '努力加载中'
})
const inputVal = ref(0)
const totalSaveMoney = ref<any>(null) //节省的的价格
const show = ref(false)
const showPop = ref(false)
const orderId = ref()
const desc = ref('') //小料信息
const count = ref(0) //小料信息
const loading = ref(true) //小料信息
const isEmpty = ref(false) //预加载
const isFirstLoad = ref(true) // 首次加载标志
//存储用户支付密码
const payPassword = ref('')
const clBalance = ref(0)
const errorInfo = ref('')
// 是否显示余额密码弹出框
const showYePay = ref(false)
// 是否显示密码数字框
const showKeyboard = ref(true)
// 添加支付状态标志
const isPaying = ref(false) // 防止重复提交

// 校验电话号码的方法
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 中国大陆手机号正则表达式

  if (!phone.value) {
    phoneError.value = '联系电话不能为空'
    phoneErrorStatus.value = true
  } else if (!phoneRegex.test(phone.value)) {
    phoneError.value = '请输入有效的手机号码'
    phoneErrorStatus.value = true
  } else {
    phoneError.value = '' // 清除错误信息
    phoneErrorStatus.value = false
  }

  // debouncedHandleDeductionsChange()
}

//#region ***************** 商品价格 *************************/

//商品节省{{ enumAll.SHOPMODEL[shopMode] }}
watch(
  () => totalSaveMoney.value,
  (newData) => {
    if (
      Number(formatPrice(availableTicket.value)) >= newData &&
      newData != null
    ) {
      deductions.value = newData
      // inputVal.value = newData
      totalSaveMoney.value = newData
    } else {
      deductions.value = Number(formatPrice(availableTicket.value))
      totalSaveMoney.value = Number(formatPrice(availableTicket.value))
    }
  }
)

watch(
  () => phone.value,
  (newVal, oldVal) => {
    if (isFirstLoad.value) {
      isFirstLoad.value = false
      return
    }
    console.log(newVal, oldVal, 'phone.value')

    if (newVal !== oldVal) {
      debouncedHandleDeductionsChange()
    }
  }
)

//更改{{ enumAll.SHOPMODEL[shopMode] }}抵扣
const handleFlqValChange = (score?: any) => {
  if (score !== undefined) {
    // 确保值是正确的数字类型
    const numericValue =
      typeof score === 'string' ? parseFloat(score) : Number(score)

    deductions.value = isNaN(numericValue) ? 0 : numericValue
  }
}
// 添加新的事件处理函数
const onStepperChange = (value: number) => {
  // 确保值在有效范围内
  const maxValue = Number(formatPrice1(totalSaveMoney.value))
  if (value > maxValue) {
    deductions.value = maxValue
  } else if (value < 0) {
    deductions.value = 0
  }
  debouncedHandleDeductionsChange()
}

// stepper 失去焦点时调用
const onStepperBlur = () => {
  // if (phone.value && phone.value.length === 11) {
  //   validatePhone()
  //   if (!phoneErrorStatus.value) {
  //     debouncedGetOrderMoney() // 使用防抖函数
  //   }
  // }
  debouncedHandleDeductionsChange()
}

// 创建防抖函数，延迟500ms执行
const debouncedGetOrderMoney = debounce(() => {
  getOrderMoney()
}, 500)
// 格式化金额为两位小数
function formatPrice(value: number): string {
  const factor = 100
  value = Math.floor(value * factor) / factor

  return value.toFixed(2)
}
// 格式化金额为1位小数
function formatPrice1(value: number): string {
  const factor = 10
  value = Math.floor(value * factor) / factor

  return value.toFixed(1)
}
// #endregion

// #region ***************** 创建订单 *************************/
// 创建防抖版本的处理函数
const debouncedHandleDeductionsChange = debounce(() => {
  if (
    phone.value &&
    phone.value.length === 11 &&
    Number(deductions.value) >= 0
  ) {
    validatePhone()
    if (!phoneErrorStatus.value) {
      getOrderMoney()
    }
  }
}, 500)

// 监听电话号码和抵扣金额变化

const handleEatTypeChange = (val: any) => {
  orderData.value.eatType = val
}

//订单数据
const getOrderMoney = async (score?: any) => {
  if (phone.value == '') {
    return uni.showToast({
      title: '请填写手机号码',
      icon: 'none'
    })
  }

  // console.log('订单数据==》', chooseGoods.value, desc.value, deductions.value)
  let orderProductSkus = chooseGoods.value.map((item: any) => {
    count.value = item.num
    let obj = {
      money: item.productPrice,
      moneyUnit: null,
      count: item.num,
      shopProductSkuId: item.shopProductSkuId,
      // 小料
      otherStr: '',
      otherCheckStr: ''
    }
    //每个小料details不同
    switch (shopData.value.shopBrandId) {
      case '13': //瑞幸 otherStr:SP2077-00169
        if (item.details.otherStr) {
          obj.otherStr = item.details.otherStr
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break
      case '41': //库迪 otherStr:SP2418-00001
        if (item.details.otherStr) {
          obj.otherStr = item.details.otherStr
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break
      case '10': //星巴克   [{"specificationId":"规格id","skuId":"辅料id"}]
        if (
          item.details.otherStr &&
          Array.isArray(item.details.otherStr) &&
          item.details.otherStr.length > 0
        ) {
          obj.otherStr = JSON.stringify(item.details.otherStr)
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break
      case '19': //喜茶 otherStr:"[1656,518,38]"
        if (
          item.details.otherStr &&
          Array.isArray(item.details.otherStr) &&
          item.details.otherStr.length > 0
        ) {
          obj.otherStr = JSON.stringify(
            item.details.otherStr.map((e: any) => e.skuId)
          )
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break
      case '2': //奈雪的茶otherStr:  "{"accessoriesCode":["P_4TWTZC83AS5C","P_4TWTZC83AS5D"],"skuCode":"P_4TWTZC8ASH8N"}"  accessoriesCode:加料code集合，skuCode：辅料组合code
        if (item.details.otherStr) {
          obj.otherStr = JSON.stringify(item.details.otherStr)
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break
      case '5': //麦当劳   [{"specificationId":"规格id","skuId":"辅料id"}]
        if (
          item.details.otherStr &&
          Array.isArray(item.details.otherStr) &&
          item.details.otherStr.length > 0
        ) {
          obj.otherStr = JSON.stringify(item.details.otherStr)
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break
      case '1': //肯德基  [{"specificationId":"规格id","skuId":"辅料id"}]
        if (
          item.details.otherStr &&
          Array.isArray(item.details.otherStr) &&
          item.details.otherStr.length > 0
        ) {
          obj.otherStr = JSON.stringify(item.details.otherStr)
          obj.otherCheckStr = item.details.otherCheckStr
        } else {
          obj.otherStr = ''
        }
        break

      default:
        obj.otherStr = ''
        break
    }
    return obj
  })
  let obj = {
    orderProductSkus,
    status: 0,
    scoreMoney: Number(deductions.value),
    contactNumber: phone.value,
    shopBrandId: shopData.value.shopBrandId,
    restaurantId: shopData.value.restaurantId,
    eatType: checked.value,
    integralsRuleId: 5 //大牌生活必传
  }
  isEmpty.value = false
  try {
    uni.showLoading({ title: '折扣计算中请稍后', mask: true })
    const { data, code } = await orderApi.orderMoney(obj).finally(() => {
      uni.hideLoading()
    })
    const { orderMonies, totalMoney, payMoney, money, moneyUnit } = data
    orderData.value = { ...obj }
    orderData.value.orderMonies = orderMonies
    orderData.value.totalMoney = totalMoney
    orderData.value.payMoney = payMoney
    orderData.value.money = money
    orderData.value.moneyUnit = moneyUnit
    orderData.value.scoreMoney = deductions.value //写{{ enumAll.SHOPMODEL[shopMode] }}
    orderData.value.orderProductSkus = orderProductSkus //写{{ enumAll.SHOPMODEL[shopMode] }}
    otherMoney.value = data.otherMoney
    moneyGoods.value = data.orderProductSkus
    loading.value = false
  } catch (error: any) {
    loadText.value.loading = '接口报错,请返回重新选择=>' + error.msg
    loading.value = false
    console.log(error)
    isEmpty.value = true
  } finally {
  }
}
//创建订单
const creatOrder = async () => {
  orderData.value.integralsRuleId = 5
  console.log('创建订单准备数据==》', orderData.value)
  const { data } = await orderApi.orderAdd(orderData.value)
  // orderId.value = data.id
  goodDetailStore.setOrderId(data.id)

  if (data) {
    if (isApp.value) {
      const u = browserVersion()
      if (u.iPhone) {
        // @ts-ignore
        window.JSBridge.invoke('goPay', { orderId: data.id, money: data.money })
        shopInfoStore.setIsApp(false)
        return
      } else if (u.isAndroid) {
        // @ts-ignore
        if (window?.Android) {
          // @ts-ignore
          window?.Android?.goPay(data.id, data.money)
          shopInfoStore.setIsApp(false)
        }
        return
      }
    } else {
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
    }
  }
}

// #endregion
// #region ***************** 优惠计算 ************************* /
const getDiscountTicket = async () => {
  try {
    if (shopMode.value == 1) {
      // 花积分模式
      const { data } = await moneyApi.getMemberSomeWalletMoney({
        walletRule: enumAll.wallet_rule_id_enum.花积分钱包
      })
      hlhyTicket.value = data
      flqTicket.value = 0
      clTicket.value = 0
    } else if (shopMode.value == 4) {
      // 复来券模式
      const { data } = await moneyApi.getMemberTotalFulaiquan()
      flqTicket.value = data
      hlhyTicket.value = 0
      clTicket.value = 0
    } else if (shopMode.value == 6) {
      // 长来模式
      const { data } = await moneyApi.getMemberSomeWalletMoney({
        walletRule: enumAll.wallet_rule_id_enum.现金抵用券
      })
      clTicket.value = data
      // console.log(data, '用户拥有的总的现金抵用券')
      hlhyTicket.value = 0
      flqTicket.value = 0
    }
  } catch (error) {
    console.error('获取优惠券失败:', error)
    flqTicket.value = 0
    hlhyTicket.value = 0
    clTicket.value = 0
  }
}

// 计算当前可用的优惠券金额
const availableTicket = computed(() => {
  switch (Number(shopMode.value)) {
    case 1:
      return hlhyTicket.value
    case 4:
      return flqTicket.value
    case 6:
      return clTicket.value
    default:
      return 0
  }
})

// #endregion

// #region ***************** 支付 *************************/
// 创建防抖版本的 creatOrder 函数，500 毫秒内只执行一次
const debouncedCreatOrder = debounce(creatOrder, 500)
const onsubmit = () => {
  if (!phoneErrorStatus.value) {
    //创建订单
    // 调用防抖函数
    debouncedCreatOrder()
  } else {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
  }
}
// #endregion

// #region ***************** 刷新 *************************/
const onClickRight = () => {
  // 显示加载提示
  uni.showToast({
    title: '刷新中...',
    icon: 'loading',
    duration: 2000
  })

  // 重新加载页面数据
  reloadPageData()
}

// 重新加载页面数据
const reloadPageData = async () => {
  try {
    // 重新获取购物车数据
    chooseGoods.value = carStore.goodsList

    // 重新获取店铺信息
    shopInfo.value = shopInfoStore.shopInfo

    // 重新获取折扣券信息
    await getDiscountTicket()

    // 重新计算总节省金额
    const rawValue = chooseGoods.value.reduce((sum: Decimal, item: any) => {
      return sum.plus(new Decimal(item.highestScoreMoney).times(item.num))
    }, new Decimal(0))

    totalSaveMoney.value = rawValue.toNumber()

    // 重新处理抵扣逻辑
    if (
      Number(formatPrice(availableTicket.value)) >= totalSaveMoney.value &&
      totalSaveMoney.value != null
    ) {
      deductions.value = totalSaveMoney.value
    } else {
      deductions.value = Number(formatPrice(availableTicket.value))
    }

    // 如果电话号码有效，重新计算订单金额
    if (phone.value && phone.value.length === 11) {
      validatePhone()
      if (!phoneErrorStatus.value) {
        await getOrderMoney()
      }
    }

    // 重新计算订单总金额
    orderData.value.payMoney = chooseGoods.value
      .reduce((sum: Decimal, item: any) => {
        let itemPrice = 0
        if (
          item.details &&
          Array.isArray(item.details.otherStr) &&
          item.details.otherStr.length > 0
        ) {
          itemPrice = item.details.otherStr.reduce(
            (acc: number, detail: any) => {
              return acc + (detail.price || 0)
            },
            0
          )
        } else if (
          item.details &&
          Array.isArray(item.details.otherStr.spu_specs) &&
          item.details.otherStr.spu_specs.length > 0
        ) {
          //奈雪的茶的价格计算
          itemPrice = item.details.otherStr.spu_specs.reduce(
            (acc: number, detail: any) => {
              return acc + (detail.price || 0)
            },
            0
          )
        } else {
          itemPrice = 0
        }
        let money = item.money + itemPrice - item.userScoreMoney
        return sum.plus(new Decimal(money).times(item.num))
      }, new Decimal(0))
      .toNumber()

    // 隐藏加载提示
    uni.hideToast()

    // 显示刷新成功提示
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000
    })
  } catch (error) {
    console.error('刷新页面数据失败:', error)
    uni.hideToast()
    uni.showToast({
      title: '刷新失败',
      icon: 'none',
      duration: 1000
    })
  }
}
// 获取长来余额
const getMemberTotalShopMoneyChang = async () => {
  const { data } = await moneyApi.getMemberSomeWalletMoney({
    walletRule: enumAll.wallet_rule_id_enum.长来余额钱包
  })
  //向下取整保留两位小数
  clBalance.value = Math.floor((Number(data) || 0) * 100) / 100
  // console.log(data, '用户的长来余额钱包')
}
//获取用户信息
const getUserDetailInfo = async () => {
  try {
    const { data } = await userApi.userInfo()
    // console.log('用户数据', data)
    // 是否有密码
    if (data.payPassword) {
      payPassword.value = data.payPassword
    } else {
      payPassword.value = ''
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}
// 跳转密码
const handleGoPassword = () => {
  uni.reLaunch({
    url: `/pages/productCheckout/shopPayPwd?restaurantId=${shopData.value.restaurantId}&shopBrandId=${shopData.value.shopBrandId}&tzPage=4`
  })
}
// 长来余额支付成功跳转
const handleGosuccess = () => {
  // 跳转支付成功页面
  uni.reLaunch({
    url: `/pages/physicalShopCheck/clyePaySuccess?isSmfk=0`
  })
}
// 长来余额支付按钮
const openClBalance = () => {
  orderData.value.moneyUnit = '长来余额钱包'
  orderData.value.shopMode = 6
  if (payPassword.value == '') {
    uni.showModal({
      title: '提示',
      content:
        '您未设置支付密码，为确保支付安全需先设置一次支付密码，后续不会再设置',
      showCancel: true,
      success: ({ confirm, cancel }) => {
        if (confirm) {
          handleGoPassword()
        } else {
        }
      }
    })
    return
  }
  // 长来余额大于实付款
  if (Number(orderData.value.payMoney) < Number(clBalance.value)) {
    showYePay.value = true
  } else {
    uni.showToast({
      icon: 'error',
      title: '来钡余额不足！'
    })
  }
}
// 余额支付确认按钮
const handleClyePaySure = async () => {
  // 防止重复点击
  if (isPaying.value) return
  // 设置支付中状态
  isPaying.value = true
  // console.log(orderData.value, '支付的orderData数据')
  uni.showLoading({ title: '支付中请等候', mask: true })
  try {
    const { data, code, mes } = await orderApi
      .orderAdd({
        ...orderData.value,
        // 不能直接将加密的支付密码赋值给orderData的payPassword，这样回导致点击确认支付后无法再删除密码
        payPassword: Md5.hashStr(orderData.value.payPassword)
      })
      .finally(() => {
        uni.hideLoading()
        isPaying.value = false // 无论成功失败都重置状态
      })
    if (code == 200) {
      uni.showToast({
        icon: 'success',
        title: '购买成功！'
      })
      orderData.value.payPassword = ''
      showYePay.value = false
      // 跳转支付成功页面
      handleGosuccess()
    } else {
      orderData.value.payPassword = ''
      showYePay.value = false
      uni.showToast({
        icon: mes,
        title: '购买失败！'
      })
    }
  } catch (e) {
    orderData.value.payPassword = ''
    console.log('余额支付error', e)
    isPaying.value = false
  }
}
// #endregion

// #region ***************** 页面周期 *************************/

onShow(() => {
  chooseGoods.value = carStore.goodsList
  shopInfo.value = shopInfoStore.shopInfo
  getUserDetailInfo()
  // if (chooseGoods.value.length > 0) {
  //     getOrderMoney()
  // }
})
onLoad(async (option: any) => {
  // console.log('大牌付款Option', option)

  isApp.value = shopStore.isApp || uni.getStorageSync('from')
  shopData.value = option
  shopMode.value = option?.shopMode
    ? option.shopMode
    : uni.getStorageSync('shopMode')
  if (shopMode.value == 6) {
    getMemberTotalShopMoneyChang()
  }
  if (option.shopBrandId == 5) checked.value = '2'
  chooseGoods.value = carStore.goodsList
  shopInfo.value = shopInfoStore.shopInfo
  orderId.value = goodDetailStore.orderId
  orderData.value.eatType = checked.value
  phone.value = userStore.userInfo.phone ? userStore.userInfo.phone : ''
  // 区分模式获取折扣券
  await getDiscountTicket()

  const rawValue = chooseGoods.value.reduce((sum: Decimal, item: any) => {
    return sum.plus(new Decimal(item.highestScoreMoney).times(item.num))
  }, new Decimal(0))

  totalSaveMoney.value = rawValue.toNumber()
  // 处理抵扣逻辑
  if (
    Number(formatPrice(availableTicket.value)) >= totalSaveMoney.value &&
    totalSaveMoney.value != null
  ) {
    deductions.value = totalSaveMoney.value
  } else {
    deductions.value = Number(formatPrice(availableTicket.value))
  }

  orderData.value.payMoney = chooseGoods.value
    .reduce((sum: Decimal, item: any) => {
      let itemPrice = 0
      if (
        item.details &&
        Array.isArray(item.details.otherStr) &&
        item.details.otherStr.length > 0
      ) {
        itemPrice = item.details.otherStr.reduce((acc: number, detail: any) => {
          return acc + (detail.price || 0)
        }, 0)
      } else if (
        item.details &&
        item.details.otherStr &&
        Array.isArray(item.details.otherStr.spu_specs) &&
        item.details.otherStr.spu_specs.length > 0
      ) {
        //奈雪的茶的价格计算
        itemPrice = item.details.otherStr.spu_specs.reduce(
          (acc: number, detail: any) => {
            return acc + (detail.price || 0)
          },
          0
        )
      } else {
        itemPrice = 0
      }
      let money = item.money + itemPrice
      return sum.plus(new Decimal(money).times(item.num))
    }, new Decimal(0))
    .toNumber()

  debouncedHandleDeductionsChange()
})

// #endregion
</script>

<style lang="scss" scoped>
.payMoney {
  // width: 100%;
  padding: 20rpx;

  .address {
    display: flex;
    align-items: center;

    // background-color: pink;
    .icon {
      color: #b7c4f2;
    }

    .address-info {
      margin-left: 20rpx;
      .title {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }

  .userInfo {
    .telBox {
      padding: 20rpx 0;

      .text2 {
        margin-left: 20rpx;
        font-size: 24rpx;
        color: #e3b888;
      }

      .telInpt {
        margin-top: 30rpx;
      }
    }

    .eatBox {
      padding: 30rpx 0;
      border-top: 2rpx solid #dde4fb;
    }

    .chooseBox {
      padding: 30rpx;
      border-radius: 20rpx;
      font-size: 30rpx;
      color: #333;
      border: 2rpx solid #dedede;
      background-color: #f7f8fa;
    }
  }

  .orderInfo {
    margin-bottom: 250rpx;

    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 30rpx;
      color: #777777;
    }

    .orderBox {
      margin: 30rpx 0;
    }

    .price1 {
      padding: 30rpx 0;
      // color: #bebebe;
      font-size: 28rpx;

      border-top: 2rpx solid #dde4fb;

      .text {
        font-weight: 700;
        // text-decoration: underline;
        color: #fa3534;
        // border-bottom: 2prx solid #409eff;
      }
    }

    .price2 {
      padding: 30rpx 0;
      color: #969799;
      font-size: 24rpx;

      border-top: 2rpx solid #dde4fb;
    }
  }

  .tijiao {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 180rpx;
    padding: 0 20rpx;
    background-color: #fff;
  }
}

.popup {
  width: 100%;
  height: 100%;
  // position: relative;
  // text-align: center;
  line-height: 150rpx;
  display: flex;
  flex-direction: column;
  // justify-content: ;
  align-items: center;

  .inputBox {
    display: flex;
    flex-direction: column;
    // justify-content: ;
    align-items: center;
  }

  .text {
    height: 100rpx;
  }

  .input {
    // position: absolute;
    // top: 50%;
    // left: 50%;
    // transform: translate(-50%, -50%);
    height: 50rpx;
    width: 250rpx;
  }
}

.card {
  width: 100%;
  padding: 20rpx;
  border-radius: 20rpx;
  background-color: #fff;
  margin: 20rpx 0;
}

.flexCenter {
  display: flex;
  // justify-content:start ;
  align-items: center;

  .icon {
    margin-right: 20rpx;
  }
}

.chooseBox-active {
  color: #fff !important;
  border: 2rpx solid #e57332 !important;
  background-color: #fef1ec !important;
}

.flexSpaceBetween {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.van-cell) {
  padding: 0 !important;
}

:deep(.van-cell__value) {
  color: #d90209;
}

:deep(.van-radio__icon--checked .van-icon) {
  background-color: #ff6b15;
  border-color: #ff6b15;
}

:deep(.van-ellipsis) {
  overflow: visible !important;
  white-space: normal !important;
  /* 允许换行 */
  text-overflow: clip !important;
  /* 不显示省略号 */
}

:deep(.van-card__desc) {
  line-height: none;
}
</style>
